<template>
    <div id="order-detail">
        <div class="action-group">
            <div>
                <a-button @click="goBack">
                    <a-icon type="left"/>返回
                </a-button>
                <a-button class="button-gap" :disabled="!readyToPrint" @click="printOrder">打印订单</a-button>
                <!-- <a-button  @click="payOrder">付款</a-button> -->
                <a-dropdown v-if="currentOrder.state==1" class="button-gap">
                    <a-menu slot="overlay" @click="payOrder">
                        <a-menu-item key="现金">现金</a-menu-item>
                        <a-menu-item key="刷卡">刷卡</a-menu-item>
                        <a-menu-item key="支付宝">支付宝</a-menu-item>
                        <a-menu-item key="微信">微信</a-menu-item>
                        <a-menu-item key="其他">其他</a-menu-item>
                    </a-menu>
                    <a-button type="primary">
                        付款
                        <a-icon type="down"/>
                    </a-button>
                </a-dropdown>
                <a-button class="button-gap" type="primary" @click="startOrder" v-if="currentOrder.state==2">交付</a-button>
                <a-button class="button-gap" type="primary" @click="finishOrder" v-if="currentOrder.state==4">完成订单</a-button>
                <a-button class="button-gap" type="danger" @click="invalidOrder" v-if="currentOrder.state!=0">作废</a-button>
            </div>
            <div>
                <a-button class="button-gap" @click="updateOrderUser" v-if="hasUserUpdate">更新用户</a-button>
                <a-button class="button-gap" @click="addReference">修改附件</a-button>
                <a-button class="button-gap" @click="editRemarks">修改备注</a-button>
            </div>
        </div>
        <div v-if="currentOrder.reference && currentOrder.reference.length > 0" style="margin-top:12px">
            <a-collapse v-model="showReference">
                <a-collapse-panel header="附件信息" key="reference">
                    <image-viewer :images="currentOrder.reference"></image-viewer>
                </a-collapse-panel>
            </a-collapse>
        </div>
        <webview id="webview" style="width: 100%;height: 100%" ref="webview" src="/orderdetail.html" nodeintegration></webview>
        <a-modal title="修改备注" v-model="showEditRemarks" @ok="onEditRemarks">
            <a-input v-model="currentOrder.remarks"></a-input>
        </a-modal>
    </div>
</template>
<script>
import { mapGetters } from 'vuex';
import moment from 'moment';
import VueBarcode from 'vue-barcode';
import { ipcRenderer } from 'electron';
import ImageViewer from '@/components/imageviewer';
import _ from 'lodash';
export default {
    data() {
        return {
            moment,
            currentOrder: {},
            currentId: '',
            printerList: [],
            defaultPrinter: '',
            readyToPrint: false,
            hasUserUpdate: false,
            showReference: [],
            showEditRemarks: false
        };
    },
    components: {
        barcode: VueBarcode,
        [ImageViewer.name]: ImageViewer
    },
    created() {
        this.currentId = this.$route.query.id;
        if (this.currentId) {
            this.$store
                .dispatch('getOrderById', this.currentId)
                .then(order => {
                    this.currentOrder = order;
                    console.log(this.currentOrder);
                    let orderUserUpdateMoment = moment(
                        this.currentOrder.user.updateDate
                    );
                    this.$store
                        .dispatch('getUserById', this.currentOrder.user.id)
                        .then(user => {
                            if (user) {
                                let dbUserUpdateMoment = moment(
                                    user.updateDate
                                );
                                if (
                                    dbUserUpdateMoment.isAfter(
                                        orderUserUpdateMoment
                                    )
                                ) {
                                    this.hasUserUpdate = true;
                                }
                            }
                        });
                })
                .catch(reason => {
                    this.$error({
                        title: reason.message,
                        onOk: () => {
                            this.$router.go(-1);
                        }
                    });
                });
        }
        // 渲染线程主动发送getPrinterList事件到主线程请求打印机列表
        ipcRenderer.send('getPrinterList');

        // 监听主线程获取到打印机列表后的回调
        ipcRenderer.once('getPrinterList', (event, data) => {
            // data就是打印机列表
            this.printerList = data;
            this.defaultPrinter = _.find(this.printerList, { isDefault: true });
            if (!this.defaultPrinter) {
                this.$error({ title: '没有找到默认打印机，可能无法打印订单' });
            }
        });
    },
    mounted() {
        const webview = this.$refs.webview;
        if (!webview) {
            return;
        }
        webview.addEventListener('dom-ready', event => {
            webview.send('ping', this.currentOrder);
        });
        webview.addEventListener('ipc-message', event => {
            if (event.channel === 'pong') {
                this.readyToPrint = true;
            }
        });
    },
    methods: {
        goBack() {
            this.$router.go(-1);
        },
        printOrder() {
            const webview = document.querySelector('webview');
            if (webview) {
                webview.print({ silent: false, printBackground: true });
            }
        },
        payOrder(e) {
            let config = {
                id: this.currentOrder.id,
                type: e.key
            };
            this.$confirm({
                centered: true,
                title: '确定客户已经支付这个订单吗？',
                onOk: () => {
                    this.$store
                        .dispatch('payOrder', config)
                        .then(() => {
                            this.$store
                                .dispatch('getOrderById', this.currentId)
                                .then(order => {
                                    this.currentOrder = order;
                                    const webview = this.$refs.webview;
                                    if (webview) {
                                        webview.send('ping', this.currentOrder);
                                    }
                                });
                        })
                        .catch(reason => {
                            this.$error({ title: reason.message });
                        });
                }
            });
        },
        startOrder() {
            this.$confirm({
                centered: true,
                title: '确定交付这个订单吗？',
                onOk: () => {
                    this.$store
                        .dispatch('startOrder', this.currentOrder)
                        .then(() => {
                            this.$store
                                .dispatch('getOrderById', this.currentId)
                                .then(order => {
                                    this.currentOrder = order;
                                    const webview = this.$refs.webview;
                                    if (webview) {
                                        webview.send('ping', this.currentOrder);
                                    }
                                });
                        });
                }
            });
        },
        updateOrderUser() {
            this.$store
                .dispatch('getUserById', this.currentOrder.user.id)
                .then(user => {
                    if (user) {
                        this.currentOrder.setUser(user);
                        this.$store
                            .dispatch('updateOrder', this.currentOrder)
                            .then(() => {
                                this.$store
                                    .dispatch('getOrderById', this.currentId)
                                    .then(order => {
                                        this.currentOrder = order;
                                        const webview = this.$refs.webview;
                                        if (webview) {
                                            webview.send(
                                                'ping',
                                                this.currentOrder
                                            );
                                        }
                                        this.hasUserUpdate = false;
                                    });
                            });
                    }
                });
        },
        invalidOrder() {
            this.$confirm({
                centered: true,
                title: '确定作废这个订单吗？',
                onOk: () => {
                    this.$store
                        .dispatch('invalidOrder', this.currentOrder)
                        .then(() => {
                            this.$router.go(-1);
                        });
                }
            });
        },
        finishOrder() {
            this.$confirm({
                centered: true,
                title: '确定完成这个订单吗？',
                onOk: () => {
                    this.$store
                        .dispatch('finishOrder', this.currentOrder)
                        .then(() => {
                            this.$store
                                .dispatch('getOrderById', this.currentId)
                                .then(order => {
                                    this.currentOrder = order;
                                    const webview = this.$refs.webview;
                                    if (webview) {
                                        webview.send('ping', this.currentOrder);
                                    }
                                });
                        });
                }
            });
        },
        editRemarks() {
            if (!this.currentOrder.remarks) {
                this.currentOrder.remarks = '';
            }
            this.showEditRemarks = true;
        },
        onEditRemarks() {
            this.showEditRemarks = false;
            if (this.currentOrder.remarks === '') {
                this.currentOrder.remarks = undefined;
            }
            this.$store.dispatch('updateOrder', this.currentOrder).then(() => {
                this.$store
                    .dispatch('getOrderById', this.currentId)
                    .then(order => {
                        this.currentOrder = order;
                        const webview = this.$refs.webview;
                        if (webview) {
                            webview.send('ping', this.currentOrder);
                        }
                        this.hasUserUpdate = false;
                    });
            });
        },
        addReference() {
            this.$store
                .dispatch('importImageToLocal')
                .then(result => {
                    let fixedImages = [];
                    if (result.length > 0) {
                        result.forEach(item => {
                            let s = _.replace(item, new RegExp(/\\/, 'g'), '/');
                            fixedImages.push('file://' + s);
                        });
                        this.currentOrder.reference = fixedImages;
                        this.$store
                            .dispatch('updateOrder', this.currentOrder)
                            .then(() => {
                                this.$store
                                    .dispatch('getOrderById', this.currentId)
                                    .then(order => {
                                        this.currentOrder = order;
                                        const webview = this.$refs.webview;
                                        if (webview) {
                                            webview.send(
                                                'ping',
                                                this.currentOrder
                                            );
                                        }
                                        this.hasUserUpdate = false;
                                    });
                            });
                    }
                })
                .catch(reason => {
                    if (reason.message !== 'canceled') {
                        this.$error({ title: reason.message });
                    }
                });
        }
    },
    computed: {
        ...mapGetters(['users', 'products', 'orders'])
    }
};
</script>
<style lang="stylus" scoped>
#order-detail {
    display: flex;
    flex-direction: column;
    font-size: 16px;
    height: 100%;

    .button-gap {
        margin: 0px 5px;
    }

    .action-group {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
    }

    .info-group {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin-top: 20px;

        .info-title {
            width: 60%;
            background-color: rgb(8, 22, 37);
            padding-left: 20px;
            line-height: 2em;
            color: white;
        }

        table {
            width: 60%;
        }
    }
}
</style>
